package com.avic.rong.userOrder.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.support.v7.app.ActionBar;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.avic.rong.BaseActivity;
import com.avic.rong.R;
import com.avic.rong.payUtil.JavaPayUtil;
import com.avic.rong.payUtil.PayVo;
import com.avic.rong.shoppingCar.activity.ShoppingCarActivity;
import com.avic.rong.userOrder.bean.AllOrderListBean;
import com.avic.rong.userOrder.event.InformUpdate;
import com.avic.rong.userOrder.viewHolder.OrderListViewHolder;
import com.avic.rong.userOrder.adapter.OrderGoodsDetailsListAdapter;
import com.avic.rong.userOrder.adapter.OrderGoodsWeiFaHuoListAdapter;
import com.avic.rong.userOrder.adapter.PayWayAdapter;
import com.avic.rong.userOrder.api.AddCarApi;
import com.avic.rong.userOrder.api.BuyAgainApi;
import com.avic.rong.userOrder.api.ConfirmReceiptApi;
import com.avic.rong.userOrder.api.GetOrderTracesApi;
import com.avic.rong.userOrder.api.OrderCancelApi;
import com.avic.rong.userOrder.api.OrderCancelPXApi;
import com.avic.rong.userOrder.api.OrderDetailApi;
import com.avic.rong.userOrder.api.PaySubmitApi;
import com.avic.rong.userOrder.api.PaySubmitPXApi;
import com.avic.rong.userOrder.api.ToPayApi;
import com.avic.rong.userOrder.api.ToPayPXApi;
import com.avic.rong.userOrder.bean.BuyAgainBean;
import com.avic.rong.userOrder.bean.DetailsEvaluateBean;
import com.avic.rong.userOrder.bean.OrderDetailsBean;
import com.avic.rong.userOrder.bean.PayWayBean;
import com.avic.rong.utils.ConstantsUtils;
import com.avic.rong.utils.DateUtils;
import com.avic.rong.utils.DeviceUtils;
import com.avic.rong.utils.DialogCustom;
import com.avic.rong.utils.MoneyShowUtils;
import com.avic.rong.utils.SharedPreferencesUtil;
import com.avic.rong.utils.ToastTools;
import com.avic.rong.wedgit.loadingLayout.LoadingLayout;
import com.example.minato.minastore.BaseResultEntity;
import com.example.minato.minastore.http.HttpManager;
import com.example.minato.minastore.listener.HttpOnNextListener;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;

public class OrderDetailsActivity extends BaseActivity {

    @BindView(R.id.tv_user_name)
    TextView tvUserName;
    @BindView(R.id.tv_address_phone)
    TextView tvAddressPhone;
    @BindView(R.id.tv_address_name)
    TextView tvAddressName;
    @BindView(R.id.ll_edit_address)
    LinearLayout llEditAddress;
    @BindView(R.id.fahuo_recy_list)
    RecyclerView fahuo_recy_list;
    @BindView(R.id.weifahuo_recy_list)
    RecyclerView weifahuo_recy_list;
    @BindView(R.id.tv_look_wuliu)
    TextView tv_look_wuliu;
    @BindView(R.id.tv_confirm_shouhuo)
    TextView tv_confirm_shouhuo;

    @BindView(R.id.loading_layout)
    LoadingLayout loading_layout;
    @BindView(R.id.tv_order_number)
    TextView tvOrderNumber;
    @BindView(R.id.tv_order_time)
    TextView tvOrderTime;
    @BindView(R.id.tv_order_price)
    TextView tvOrderPrice;
    @BindView(R.id.tv_pay_way)
    TextView tvPayWay;
    @BindView(R.id.tv_fapiao_type)
    TextView tvFapiaoType;
    @BindView(R.id.tv_fapiao_message)
    TextView tvFapiaoMessage;
    @BindView(R.id.tv_fapiao_taitou)
    TextView tvFapiaoTaitou;
    @BindView(R.id.tv_fapiao_start)
    TextView tvFapiaoStart;
    @BindView(R.id.tv_goods_allprice)
    TextView tvGoodsAllprice;
    @BindView(R.id.tv_youhui_price)
    TextView tvYouhuiPrice;
    @BindView(R.id.tv_member_price)
    TextView tvMemberPrice;
    @BindView(R.id.tv_yunfei_price)
    TextView tvYunfeiPrice;
    @BindView(R.id.tv_real_price)
    TextView tvRealPrice;
    @BindView(R.id.iv_order_state)
    ImageView ivOrderState;
    @BindView(R.id.tv_order_state)
    TextView tvOrderState;
    @BindView(R.id.ll_order_state)
    LinearLayout ll_order_state;
    @BindView(R.id.tv_update_fapiao)
    TextView tv_update_fapiao;
    @BindView(R.id.tv_cancel_order)
    TextView tv_cancel_order;
    @BindView(R.id.tv_look_fapiao)
    TextView tv_look_fapiao;
    @BindView(R.id.tv_urge_fahuo)
    TextView tv_urge_fahuo;
    @BindView(R.id.tv_pingjia)
    TextView tv_pingjia;
    @BindView(R.id.tv_pay)
    TextView tv_pay;
    @BindView(R.id.tv_again_buy)
    TextView tv_again_buy;
    @BindView(R.id.tv_upload_proof)
    TextView tvUploadProof;
    @BindView(R.id.tv_look_address)
    TextView tvLookAddress;
    @BindView(R.id.tv_recover_order)
    TextView tvRecoverOrder;
    @BindView(R.id.rl_fapiao)
    RelativeLayout rl_fapiao;
    @BindView(R.id.ll_complete_hint)
    LinearLayout ll_complete_hint;
    private PopupWindow popupWindow;
    private RelativeLayout rl_close;
    private ImageView iv_goods_error;
    private RelativeLayout rl_goods_error;
    private ImageView iv_fapiao_error;
    private RelativeLayout rl_fapiao_error;
    private ImageView iv_not;
    private RelativeLayout rl_not;
    private ImageView iv_qita;
    private RelativeLayout rl_qita;
    private TextView tv_kaolv;
    private TextView tv_submit;
    private int SELECT_CHECK = -1;
    private String order_id;


    private List<OrderDetailsBean.DeliveryListBean> deliveryList = new ArrayList<>();
    private List<OrderDetailsBean.ItemListBean> itemList = new ArrayList<>();
    private List<OrderDetailsBean.ItemListBean> itemListScreen = new ArrayList<>();
    private OrderGoodsDetailsListAdapter orderGoodsDetailsListAdapter;
    private OrderGoodsWeiFaHuoListAdapter orderGoodsWeiFaHuoListAdapter;
    //再次购买
    private int AGAINBUY = 100;
    private int orderType = -1;

    private List<PayWayBean.PaymentListBean> paymentList = new ArrayList<>();
    private PayWayAdapter payWayAdapter;

    private boolean isAgreement = true;//勾选用户协议

    private int payId = -1;

    private int orderId = -1;
    private String orderSn = null;
    private JavaPayUtil javaPayUtil;

    private OrderDetailsBean.OrderBean order;
    private OrderDetailsBean orderDetailsBean;

    public static String ORDER_JUMP = "orderJump";
    public static String ORDER_LIST_JUMP = "order_LIst_JUMP";
    private String orderListjump;

    private String orderMinehome;
    private OrderDetailsBean.InvoiceBean invoice;


    private AllOrderListBean.OrderListBean.ItemsViewBean itemsViewBeanEvaluate;
    private AllOrderListBean.OrderListBean moreGoodBeanEvaluate;
    private AllOrderListBean.OrderListBean goodBeanEvaluate;

    @Override
    protected int getContentViewId() {
        return R.layout.activity_order_details;
    }

    @Override
    protected void initView() {
        ivRight.setImageResource(R.mipmap.gouwuche_dot);
        if (TextUtils.isEmpty(getIntent().getStringExtra(OrderListViewHolder.ORDER_ID))) {
            finish();
        } else {
            order_id = getIntent().getStringExtra(OrderListViewHolder.ORDER_ID);
        }
        tvTitle.setText("订单详情");

        orderMinehome = getIntent().getStringExtra(ORDER_JUMP);
        orderListjump = getIntent().getStringExtra(ORDER_LIST_JUMP);


        //用作评价数据传递
        moreGoodBeanEvaluate = (AllOrderListBean.OrderListBean) getIntent().getSerializableExtra("more_goods_order");
        itemsViewBeanEvaluate = (AllOrderListBean.OrderListBean.ItemsViewBean) getIntent().getSerializableExtra("goods_order");
        goodBeanEvaluate = (AllOrderListBean.OrderListBean) getIntent().getSerializableExtra("good_bean");

//        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this,
//                LinearLayoutManager.VERTICAL, false) {
//            @Override
//            public boolean canScrollVertically() {
//                return false;
//            }
//        };
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };

        fahuo_recy_list.setLayoutManager(linearLayoutManager);
        orderGoodsDetailsListAdapter = new OrderGoodsDetailsListAdapter(this, deliveryList);
        fahuo_recy_list.setAdapter(orderGoodsDetailsListAdapter);
        LinearLayoutManager linearLayoutManagerWeiFaHuo = new LinearLayoutManager(context) {
            @Override
            public boolean canScrollVertically() {
                return false;
            }
        };

        weifahuo_recy_list.setLayoutManager(linearLayoutManagerWeiFaHuo);
        orderGoodsWeiFaHuoListAdapter = new OrderGoodsWeiFaHuoListAdapter(this, itemListScreen);
        weifahuo_recy_list.setAdapter(orderGoodsWeiFaHuoListAdapter);


        initData();
    }

    private void initData() {
        //取消订单需要刷新当前页，把底部按钮变为初始状态

        tv_look_fapiao.setVisibility(View.GONE);
        tv_look_wuliu.setVisibility(View.GONE);
        tv_confirm_shouhuo.setVisibility(View.GONE);

        tv_pingjia.setVisibility(View.GONE);
        tv_again_buy.setVisibility(View.GONE);
        tv_update_fapiao.setVisibility(View.GONE);
        tv_cancel_order.setVisibility(View.GONE);
        tv_pay.setVisibility(View.GONE);
        tv_urge_fahuo.setVisibility(View.GONE);
        tvUploadProof.setVisibility(View.GONE);
        tvLookAddress.setVisibility(View.GONE);
        tvRecoverOrder.setVisibility(View.GONE);
        ll_complete_hint.setVisibility(View.GONE);


        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> map = new HashMap<>();
            map.put("orderId", order_id);
            map.put("token", getSharedPreferencesUtil().getLogintoken());
            final OrderDetailApi orderDetailApi = new OrderDetailApi(this, simpleOnNextListener);
            orderDetailApi.setCache(false);
            orderDetailApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(orderDetailApi);

            loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    HttpManager.getInstance().doHttpDeal(orderDetailApi);
                    loading_layout.setStatus(LoadingLayout.LOADING);
                }

                @Override
                public void onReturn(View v) {
                    onBackPressed();
                }
            });
            loading_layout.setStatus(LoadingLayout.LOADING);
        } else {
            loading_layout.setStatus(LoadingLayout.EMPTY);
        }
    }

    @Override
    protected void addListener() {
        //取消订单
        tv_cancel_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancleOrder();
            }
        });

        ivBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!TextUtils.isEmpty(orderMinehome) && orderMinehome.equals("mine_home")) {
                    finish();

                } else if (!TextUtils.isEmpty(orderListjump) && orderListjump.equals("order_list")) {
                    finish();
                } else {
                    Intent intent = new Intent(OrderDetailsActivity.this, MineOrderActivity.class);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    startActivity(intent);
                }

            }
        });
        rl_fapiao.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (order != null && invoice != null) {
                    if (order.getInvId() == 0 || invoice.getStatus() == 8) {
                        return;
                    } else {
                        Intent intent = new Intent(context, FaPiaoDetailsActivity.class);
                        intent.putExtra("order_id", order.getOrderId() + "");
                        intent.putExtra("order_type", order.getOrderType() + "");
                        startActivity(intent);
                    }
                }
            }
        });
    }

    private void cancleOrder() {
        View inflate = LayoutInflater.from(this).inflate(R.layout.cancle_order_pop, null);
        rl_close = inflate.findViewById(R.id.rl_close);
        iv_goods_error = inflate.findViewById(R.id.iv_goods_error);
        rl_goods_error = inflate.findViewById(R.id.rl_goods_error);
        iv_fapiao_error = inflate.findViewById(R.id.iv_fapiao_error);
        rl_fapiao_error = inflate.findViewById(R.id.rl_fapiao_error);
        iv_not = inflate.findViewById(R.id.iv_not);
        rl_not = inflate.findViewById(R.id.rl_not);
        iv_qita = inflate.findViewById(R.id.iv_qita);
        rl_qita = inflate.findViewById(R.id.rl_qita);
        tv_kaolv = inflate.findViewById(R.id.tv_kaolv);
        tv_submit = inflate.findViewById(R.id.tv_submit);
        commonPop(inflate);
        rl_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        rl_goods_error.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_goods_error.setSelected(true);
                iv_fapiao_error.setSelected(false);
                iv_not.setSelected(false);
                iv_qita.setSelected(false);
                SELECT_CHECK = 1;
                tv_submit.setBackgroundResource(R.drawable.shape_right_r20_green);
            }
        });
        rl_fapiao_error.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_goods_error.setSelected(false);
                iv_fapiao_error.setSelected(true);
                iv_not.setSelected(false);
                iv_qita.setSelected(false);
                SELECT_CHECK = 2;
                tv_submit.setBackgroundResource(R.drawable.shape_right_r20_green);
            }
        });
        rl_not.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_goods_error.setSelected(false);
                iv_fapiao_error.setSelected(false);
                iv_not.setSelected(true);
                iv_qita.setSelected(false);
                SELECT_CHECK = 3;
                tv_submit.setBackgroundResource(R.drawable.shape_right_r20_green);
            }
        });
        rl_qita.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_goods_error.setSelected(false);
                iv_fapiao_error.setSelected(false);
                iv_not.setSelected(false);
                iv_qita.setSelected(true);
                SELECT_CHECK = 4;
                tv_submit.setBackgroundResource(R.drawable.shape_right_r20_green);
            }
        });
        tv_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancleOrderReq(SELECT_CHECK);
            }
        });
        tv_kaolv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });

    }

    private void cancleOrderReq(int type) {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> map = new HashMap<>();
            if (TextUtils.isEmpty(order_id)) {
                return;
            }
            map.put("orderId", order_id);

            map.put("token", getSharedPreferencesUtil().getLogintoken());
            map.put("type", type + "");
            final OrderCancelApi orderCancelApi = new OrderCancelApi(this, simpleOnNextListenerCancleOrder);
            orderCancelApi.setCache(false);
            orderCancelApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(orderCancelApi);

            loading_layout.setOnReloadListener(new LoadingLayout.OnReloadListener() {
                @Override
                public void onReload(View v) {
                    HttpManager.getInstance().doHttpDeal(orderCancelApi);
                    loading_layout.setStatus(LoadingLayout.LOADING);
                }

                @Override
                public void onReturn(View v) {
                    onBackPressed();
                }
            });
            loading_layout.setStatus(LoadingLayout.LOADING);
        } else {
            loading_layout.setStatus(LoadingLayout.EMPTY);
        }
    }

    private void commonPop(View view) {
        popupWindow = new PopupWindow(view, ActionBar.LayoutParams.MATCH_PARENT, ActionBar.LayoutParams.WRAP_CONTENT, true);
        // 产生背景变暗效果
        WindowManager.LayoutParams lp = getWindow()
                .getAttributes();
        lp.alpha = 0.4f;
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        getWindow().setAttributes(lp);
        popupWindow.setBackgroundDrawable(new BitmapDrawable());
        popupWindow.setOutsideTouchable(false);
        popupWindow.setTouchable(true);
        //从下往上弹出动画效果
        popupWindow.setAnimationStyle(R.style.bottomPopupAnimation);
        popupWindow.showAtLocation(findViewById(R.id.ll_root), Gravity.BOTTOM, 0, 0);
        popupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {

            // 在dismiss中恢复透明度
            public void onDismiss() {
                WindowManager.LayoutParams lp = getWindow()
                        .getAttributes();
                lp.alpha = 1f;
                getWindow().addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
                getWindow().setAttributes(lp);
            }
        });
    }

    //权威评测
    HttpOnNextListener simpleOnNextListener = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            deliveryList.clear();
            itemList.clear();
            itemListScreen.clear();
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(OrderDetailsActivity.this, subjects.getMsg());
                return;
            }
            loading_layout.setStatus(LoadingLayout.SUCCESS);
            if ((OrderDetailsBean) subjects.getData() != null) {


                orderDetailsBean = (OrderDetailsBean) subjects.getData();
                OrderDetailsBean.AddressBean address = orderDetailsBean.getAddress();
                tvUserName.setText(address.getConsignee());
                tvAddressPhone.setText(address.getTel());
                tvAddressName.setText("地址： " + address.getProvinceName() + address.getCityName() + address.getAddress());


                order = orderDetailsBean.getOrder();
                tvOrderNumber.setText(order.getOrderSn() + "");
                String time = timeStamp2Date(order.getAddTime(), null);
                tvOrderTime.setText(time + "");
                tvOrderPrice.setText("¥" + order.getGoodsAmount() + "");

                tvPayWay.setText(order.getPayName());


                //总计折扣
                tvYouhuiPrice.setText("- ¥" + order.getDiscount());
                //使用余额
                tvMemberPrice.setText("- ¥" + order.getSurplus());
                tvGoodsAllprice.setText("¥" + order.getGoodsAmount() + "");
                tvYunfeiPrice.setText("+ ¥" + order.getShippingFee() + "");

                deliveryList.addAll(orderDetailsBean.getDeliveryList());

                itemList.addAll(orderDetailsBean.getItemList());
                if (itemList.size() > 0) {
                    for (int i = 0; i < itemList.size(); i++) {
                        OrderDetailsBean.ItemListBean itemListBean = itemList.get(i);
                        if (itemListBean.getGoodsNumber() > itemListBean.getSendNumber()) {
                            itemListScreen.add(itemListBean);
                        }
                    }

                }
                if (deliveryList.size()>0){
                    fahuo_recy_list.setVisibility(View.VISIBLE);
                }else {
                    fahuo_recy_list.setVisibility(View.GONE);
                }
                if (itemListScreen.size() > 0) {
                    weifahuo_recy_list.setVisibility(View.VISIBLE);
                } else {
                    weifahuo_recy_list.setVisibility(View.GONE);
                }
                orderGoodsDetailsListAdapter.setOrderDetailsBean(orderDetailsBean);
                orderGoodsWeiFaHuoListAdapter.setOrderDetailsBean(orderDetailsBean);
                orderGoodsDetailsListAdapter.notifyDataSetChanged();
                orderGoodsWeiFaHuoListAdapter.notifyDataSetChanged();


                invoice = orderDetailsBean.getInvoice();
//                发票类型invType： 2：增值税专用发票  3 : 电子发票
                if (invoice.getInvType() == 2) {
                    tvFapiaoType.setText("增值税专用发票");
                } else if (invoice.getInvType() == 3) {
                    tvFapiaoType.setText("电子普通发票");
                }
                tvFapiaoMessage.setText(invoice.getInvContent());
//                发票抬头invPayeeType： 1：个人  2：单位
                if (invoice.getInvPayeeType() == 1) {
                    tvFapiaoTaitou.setText("个人");
                } else if (invoice.getInvPayeeType() == 2) {
                    if (!invoice.getInvPayee().equals("null")){
                        tvFapiaoTaitou.setText(dealString(invoice.getInvPayee()));
                    }

                }


                if (invoice.getStatus() == 0 && invoice.getInvId() != 0) {
                    //未付款
                    tvFapiaoStart.setText("未付款");
                } else if (invoice.getStatus() == 1) {
                    //已开发票
                    tvFapiaoStart.setText("已开发票");

                } else if (invoice.getStatus() == 3 || invoice.getStatus() == 4 || invoice.getStatus() == 5 || invoice.getStatus() == 6 || invoice.getStatus() == 7) {
                    //开票中
                    tvFapiaoStart.setText("开票中");
                } else if (invoice.getStatus() == 9 || invoice.getStatus() == 10 || invoice.getStatus() == 11 || invoice.getStatus() == 13) {
                    //发票红冲中
                    tvFapiaoStart.setText("发票红冲中");
                } else if (invoice.getStatus() == 12) {
                    //发票已红冲
                    tvFapiaoStart.setText("发票已红冲");
                } else if (order.getInvId() == 0 || invoice.getStatus() == 8) {
                    //无需开票
                    tvFapiaoStart.setText("无需开票");
                }

                tvRealPrice.setText("¥" + MoneyShowUtils.dealNumber((Double.parseDouble(order.getOrderAmount()) - Double.parseDouble(order.getSurplus())) + ""));
                int orderStatus = order.getOrderStatus();
                int payStatus = order.getPayStatus();
                int shippingStatus = order.getShippingStatus();
                if (orderStatus == 5) {
                    //交易成功
                    tvOrderState.setText("订单状态:  交易成功");
                    ivOrderState.setImageResource(R.mipmap.icon_jiaoyi_chenggong);
                    ll_order_state.setBackground(context.getResources().getDrawable(R.mipmap.ic_jiaoyi_succeed_bg));
                    ll_complete_hint.setVisibility(View.VISIBLE);
                   /* tv_pingjia.setVisibility(View.VISIBLE);
                    tv_look_fapiao.setVisibility(View.VISIBLE);
                    tv_again_buy.setVisibility(View.VISIBLE);

                    tv_look_wuliu.setVisibility(View.GONE);
                    tv_confirm_shouhuo.setVisibility(View.GONE);
                    tv_urge_fahuo.setVisibility(View.GONE);
                    tv_update_fapiao.setVisibility(View.GONE);
                    tv_cancel_order.setVisibility(View.GONE);
                    tv_pay.setVisibility(View.GONE);*/
                } else if (orderStatus == 2) {
                    // 交易关闭
                    tvOrderState.setText("订单状态:  交易关闭");
                    ivOrderState.setImageResource(R.mipmap.icon_jiaoyi_guanbi);
                    ll_order_state.setBackground(context.getResources().getDrawable(R.mipmap.ic_jiaoyi_close));
                } else {
                    if (payStatus == 3) {
                        //处理中
                    }
                    if (payStatus < 2) {
                        //待付款
                        tvOrderState.setText("订单状态:  等待付款");
                        ivOrderState.setImageResource(R.mipmap.icon_daifukuan);
                        ll_order_state.setBackground(context.getResources().getDrawable(R.mipmap.ic_dai_fukuan_bg));

                        //当订单状态为待付款时，余额显示为零
                        tvMemberPrice.setText("- ¥" + "0.00");
                        tvRealPrice.setText("¥" + MoneyShowUtils.dealNumber(Double.parseDouble(order.getOrderAmount()) + ""));
                       /* tv_update_fapiao.setVisibility(View.VISIBLE);
                        tv_cancel_order.setVisibility(View.VISIBLE);
                        tv_pay.setVisibility(View.VISIBLE);

                        tv_look_fapiao.setVisibility(View.GONE);
                        tv_look_wuliu.setVisibility(View.GONE);
                        tv_confirm_shouhuo.setVisibility(View.GONE);
                        tv_pingjia.setVisibility(View.GONE);
                        tv_again_buy.setVisibility(View.GONE);
                        tv_urge_fahuo.setVisibility(View.GONE);*/
                    }
                    if (payStatus == 2 && (shippingStatus == 0 || shippingStatus == 3)) {
                        //待发货
                        tvOrderState.setText("订单状态:  等待发货");
                        ivOrderState.setImageResource(R.mipmap.icon_dai_fahuo);
                        ll_order_state.setBackground(context.getResources().getDrawable(R.mipmap.ic_dai_fahuo_bg));

                       /* tv_look_fapiao.setVisibility(View.VISIBLE);
                        tv_urge_fahuo.setVisibility(View.VISIBLE);

                        tv_look_wuliu.setVisibility(View.GONE);
                        tv_confirm_shouhuo.setVisibility(View.GONE);
                        tv_pingjia.setVisibility(View.GONE);
                        tv_again_buy.setVisibility(View.GONE);
                        tv_update_fapiao.setVisibility(View.GONE);
                        tv_cancel_order.setVisibility(View.GONE);
                        tv_pay.setVisibility(View.GONE);*/
                    }
                    if (shippingStatus == 1) {
                        //待收货
                        tvOrderState.setText("订单状态:  等待收货");
                        ivOrderState.setImageResource(R.mipmap.icon_daishouhuo);
                        ll_order_state.setBackground(context.getResources().getDrawable(R.mipmap.ic_dai_shouhuo_bg));


                        /*tv_look_fapiao.setVisibility(View.VISIBLE);
                        tv_look_wuliu.setVisibility(View.VISIBLE);
                        tv_confirm_shouhuo.setVisibility(View.VISIBLE);

                        tv_pingjia.setVisibility(View.GONE);
                        tv_again_buy.setVisibility(View.GONE);
                        tv_update_fapiao.setVisibility(View.GONE);
                        tv_cancel_order.setVisibility(View.GONE);
                        tv_pay.setVisibility(View.GONE);
                        tv_urge_fahuo.setVisibility(View.GONE);*/
                    }

                }


                int orderType = order.getOrderType();
                int orderId = order.getOrderId();
                String payId = order.getPayId();
                int invId = order.getInvId();
                int shippingId = order.getShippingId();
                if (orderType != 5) {
                    if (payStatus < 2 && !"1".equals(payId)) {
//                取消订单
                        tv_cancel_order.setVisibility(View.VISIBLE);
                    }
                    if (!TextUtils.isEmpty(invId + "") && payStatus == 2 && invId > 0) {
//                查看发票
                        tv_look_fapiao.setVisibility(View.VISIBLE);
                    }
                    if (orderStatus == 0 && orderType != 2 && orderType != 3) {
//                去付款
                        tv_pay.setVisibility(View.VISIBLE);
                    }
                    if (orderStatus == 1 && payStatus <= 1) {
                        if (!"1".equals(payId) && !"4".equals(payId)) {
//                    去付款
                            tv_pay.setVisibility(View.VISIBLE);
                        }
                        if ("4".equals(payId)) {
//                    上传支付凭证
                            tvUploadProof.setVisibility(View.VISIBLE);
                        }
                    }
                    if (shippingStatus == 3) {
//                催促发货(请与网站运营人员联系，联系电话4006-618-301)
                        tv_urge_fahuo.setVisibility(View.VISIBLE);
                    }
                    if (shippingStatus == 0 && payStatus == 2 && orderStatus != 5) {
//                催促发货(请与网站运营人员联系，联系电话4006-618-301)
                        tv_urge_fahuo.setVisibility(View.VISIBLE);
                    }
                    if (shippingStatus == 1) {
//                确认收货
                        tv_confirm_shouhuo.setVisibility(View.VISIBLE);
                    }
                    if (orderStatus != 5 && shippingId == 4) {
//                查看取货地址
                        tvLookAddress.setVisibility(View.VISIBLE);
//                tv_look_wuliu.setVisibility(View.VISIBLE);
                    }
                    if (orderStatus == 5 || orderStatus == 2) {
//                再次购买
                        tv_again_buy.setVisibility(View.VISIBLE);
                    }
                    if (orderStatus == 5) {
//                评价
                        tv_pingjia.setVisibility(View.VISIBLE);
                    }
                } else {//培训
                    if (orderStatus != 2) {
                        if (!TextUtils.isEmpty(invId + "") && invId > 0) {
//                    查看发票
                            tv_look_fapiao.setVisibility(View.VISIBLE);
                        }
                        if (payStatus == 0 && !"2".equals(payId)) {
//                    去付款
                            tv_pay.setVisibility(View.VISIBLE);
                        }
                        if ("2".equals(payId) && (payStatus != 2 && payStatus != 3)) {
//                    上传付款凭证
                            tvUploadProof.setVisibility(View.VISIBLE);
                        }
                        if (payStatus != 1 && payStatus != 2 && payStatus != 3) {
//                    取消订单
                            tv_cancel_order.setVisibility(View.VISIBLE);
                        }
                    } else if (orderType == 2) {
                        if ("2".equals(payId)) {
//                    恢复订单(payWay:2)
                            tvRecoverOrder.setVisibility(View.VISIBLE);
                        } else {
//                    恢复订单(payWay:0)
                            tvRecoverOrder.setVisibility(View.VISIBLE);
                        }
                    }
                }

                //查看发票
                tv_look_fapiao.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(context, FaPiaoDetailsActivity.class);
                        intent.putExtra("order_id", order.getOrderId() + "");
                        intent.putExtra("order_type", order.getOrderType() + "");
                        context.startActivity(intent);
               /* if (!Constant.getToken().isEmpty()) {
                    Map<String, String> paramsBody = new HashMap<>();
                    paramsBody.put("courseId", "4368");

                    paramsBody.put("token",Constant.getToken());
                    paramsBody.put("amount","2");
                    paramsBody.put("orderType",orderType+"");
                    final MineOrderActivity mineOrderActivity = (MineOrderActivity) context;
                    //获取支付方式
                    final OrderSubmitPXApi orderSubmitPXApi = new OrderSubmitPXApi(mineOrderActivity, simpleOnNextListenerOrderSubmitPX);
                    orderSubmitPXApi.setCache(false);
                    orderSubmitPXApi.setMap(paramsBody);
                    HttpManager.getInstance().doHttpDeal(orderSubmitPXApi);


                }*/
                    }
                });
                //修改发票
                tv_update_fapiao.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(context, UpdateFaPiaoActivity.class);
                        intent.putExtra("order_id", order.getOrderId() + "");
                        intent.putExtra("order_type", order.getOrderType() + "");
                        context.startActivity(intent);
                    }
                });
                //取消订单
                tv_cancel_order.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (orderType != 5) {
                            cancleOrder();
                        } else {
                            cancleOrderPX(context, order.getOrderSn() + "");
                        }

                    }
                });

                //催促发货   (请与网站运营人员联系，联系电话4006-618-301)
                tv_urge_fahuo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        DialogCustom.showDoubleDialog(context, "", "请与网站运营人员联系，联系电话4006-618-301", "否", "是", new DialogCustom.CustomDialogDouble() {
                            @Override
                            public void rightButtonClicked() {
                                callPhone("4006-618-301");
                            }

                            @Override
                            public void leftButtonClicked() {

                            }
                        });
                    }
                });

                //查看物流
                tv_look_wuliu.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        lookWuLiu(context, order.getOrderId() + "");

                    }
                });
                //再次购买
                tv_again_buy.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        againBuyResq(context, order.getOrderId() + "");
                    }
                });

                //上传凭证
                tvUploadProof.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(context, UploadProofActivity.class);
                        intent.putExtra("order_id", order.getOrderId() + "");
                        intent.putExtra("order_sn", order.getOrderSn() + "");
                        intent.putExtra("orderType", orderType + "");
                        context.startActivity(intent);
                    }
                });
                //评价
                tv_pingjia.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (goodBeanEvaluate!=null){
                                Intent intent = new Intent(context, OrderEvaluateActivity.class);
                                intent.putExtra("goods_order",itemsViewBeanEvaluate );
                                intent.putExtra("good_bean",goodBeanEvaluate);
                                context.startActivity(intent);

                        }else if (moreGoodBeanEvaluate!=null){
                            Intent intent = new Intent(context, MoreEvaluateActivity.class);
                            intent.putExtra("more_goods_order",moreGoodBeanEvaluate);
                            context.startActivity(intent);
                        }


                     /*   deliveryList.addAll(orderDetailsBean.getDeliveryList());

                        itemList.addAll(orderDetailsBean.getItemList());
                        if (orderDetailsBean.getDeliveryList() != null && orderDetailsBean.getDeliveryList().size() > 0) {
                            OrderDetailsBean.DeliveryListBean deliveryListBean = orderDetailsBean.getDeliveryList().get(0);
                            if (deliveryListBean.getItems() == null && deliveryListBean.getItems().size() <= 0)
                                return;
                            List<OrderDetailsBean.DeliveryListBean.ItemsBean> items = deliveryListBean.getItems();
                            if (items == null && items.size() <= 0) return;
                            OrderDetailsBean.DeliveryListBean.ItemsBean itemsBean = items.get(0);

                            DetailsEvaluateBean detailsEvaluateBean = new DetailsEvaluateBean();
                            detailsEvaluateBean.setPic(itemsBean.getGood().getGoodsImg());
                            detailsEvaluateBean.setDetailsID(order_id);
                            detailsEvaluateBean.setTitle(itemsBean.getProName());
                            detailsEvaluateBean.setSubTitle(itemsBean.getGood().getSkuName());

                            Intent intent = new Intent(context, OrderEvaluateActivity.class);
                            intent.putExtra("faHuoBean", detailsEvaluateBean);
                            context.startActivity(intent);
                        } else {
                            if (itemListScreen != null && itemListScreen.size() > 0) {
                                OrderDetailsBean.ItemListBean itemListBean = itemListScreen.get(0);
                                if (itemListScreen == null) return;
                                DetailsEvaluateBean detailsEvaluateBean = new DetailsEvaluateBean();
                                detailsEvaluateBean.setPic(itemListBean.getGood().getGoodsImg());
                                detailsEvaluateBean.setDetailsID(order_id);
                                detailsEvaluateBean.setTitle(itemListBean.getProName());
                                detailsEvaluateBean.setSubTitle(itemListBean.getGood().getSkuName());

                                Intent intent = new Intent(context, OrderEvaluateActivity.class);
                                intent.putExtra("weifaHuoBean", detailsEvaluateBean);
                                context.startActivity(intent);

                            }


                        }*/

                    }
                });
                //查看收货地址
                tvLookAddress.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(context, LookOrderAddressActivity.class);
                        context.startActivity(intent);
                    }
                });
                //去支付
                tv_pay.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        if (DateUtils.isFastDoubleClick())return;
                            if (orderType != 5) {
                                //去支付
                                toPay(orderType, order.getOrderId());
                            } else {
                                //培训去支付

                                toPayPX(orderType, order.getOrderSn());
                            }
                        }

                });
                //确认收货
                tv_confirm_shouhuo.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        configmOrder();

                    }
                });

            }

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    private void configmOrder() {
        Map<String, String> map = new HashMap<>();
        if (TextUtils.isEmpty(order_id)) return;
        map.put("orderId", order_id + "");
        map.put("token", SharedPreferencesUtil.getInstance(context).getLogintoken());
        final ConfirmReceiptApi confirmReceiptApi = new ConfirmReceiptApi(this, simpleOnNextListenerConfimOrder);
        confirmReceiptApi.setCache(false);
        confirmReceiptApi.setMap(map);
        HttpManager.getInstance().doHttpDeal(confirmReceiptApi);
    }

    //确认收货
    HttpOnNextListener simpleOnNextListenerConfimOrder = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }
            ToastTools.showToast(context, "收货成功");
            initData();
            InformUpdate informUpdate = new InformUpdate();
            informUpdate.setEventType(informUpdate.CONFIRM_SHOUHUO_INFORM);
            EventBus.getDefault().post(informUpdate);

        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());

        }
    };
    //权威评测
    HttpOnNextListener simpleOnNextListenerCancleOrder = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(OrderDetailsActivity.this, subjects.getMsg());
                return;
            }
            loading_layout.setStatus(LoadingLayout.SUCCESS);
            //刷新订单列表数据
            Intent intent = new Intent();
            setResult(RESULT_OK, intent);

            initData();
            popupWindow.dismiss();
        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
            if (e instanceof SocketTimeoutException || e instanceof ConnectException) {
                loading_layout.setStatus(LoadingLayout.NO_NETWORK);
            } else {
                loading_layout.setStatus(LoadingLayout.ERROR);
            }
        }
    };

    public static String timeStamp2Date(long time, String format) {
        if (format == null || format.isEmpty()) {
            format = "yyyy-MM-dd HH:mm:ss";
        }
        SimpleDateFormat sdf = new SimpleDateFormat(format);
        return sdf.format(new Date(time));
    }

    private void lookWuLiu(Context context, String orderId) {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> map = new HashMap<>();
            if (TextUtils.isEmpty(orderId)) {
                ToastTools.showToast(context, "没有订单ID");
                return;
            }
            map.put("orderId", orderId);

            final GetOrderTracesApi getOrderTracesApi = new GetOrderTracesApi(this, simpleOnNextListenerLookWuliu);
            getOrderTracesApi.setCache(false);
            getOrderTracesApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(getOrderTracesApi);

        }
    }

    private void cancleOrderPX(final Context context, final String orderSn) {
        View inflate = LayoutInflater.from(context).inflate(R.layout.cancle_order_pop, null);
        rl_close = inflate.findViewById(R.id.rl_close);
        iv_goods_error = inflate.findViewById(R.id.iv_goods_error);
        rl_goods_error = inflate.findViewById(R.id.rl_goods_error);
        iv_fapiao_error = inflate.findViewById(R.id.iv_fapiao_error);
        rl_fapiao_error = inflate.findViewById(R.id.rl_fapiao_error);
        iv_not = inflate.findViewById(R.id.iv_not);
        rl_not = inflate.findViewById(R.id.rl_not);
        iv_qita = inflate.findViewById(R.id.iv_qita);
        rl_qita = inflate.findViewById(R.id.rl_qita);
        tv_kaolv = inflate.findViewById(R.id.tv_kaolv);
        tv_submit = inflate.findViewById(R.id.tv_submit);
        commonPop(inflate);
        rl_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
        rl_goods_error.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_goods_error.setSelected(true);
                iv_fapiao_error.setSelected(false);
                iv_not.setSelected(false);
                iv_qita.setSelected(false);
                SELECT_CHECK = 1;
            }
        });
        rl_fapiao_error.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_goods_error.setSelected(false);
                iv_fapiao_error.setSelected(true);
                iv_not.setSelected(false);
                iv_qita.setSelected(false);
                SELECT_CHECK = 2;
            }
        });
        rl_not.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_goods_error.setSelected(false);
                iv_fapiao_error.setSelected(false);
                iv_not.setSelected(true);
                iv_qita.setSelected(false);
                SELECT_CHECK = 3;
            }
        });
        rl_qita.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                iv_goods_error.setSelected(false);
                iv_fapiao_error.setSelected(false);
                iv_not.setSelected(false);
                iv_qita.setSelected(true);
                SELECT_CHECK = 4;
            }
        });
        tv_submit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancleOrderReqPX(context, orderSn, SELECT_CHECK);
            }
        });
        tv_kaolv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });
    }

    private void cancleOrderReqPX(Context context, String orderSn, int select_check) {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> map = new HashMap<>();
            if (TextUtils.isEmpty(orderSn)) {
                ToastTools.showToast(context, "没有订单编号");
                return;
            }
            map.put("orderNumber", orderSn);

            map.put("token", getSharedPreferencesUtil().getLogintoken());

            final OrderCancelPXApi orderCancelPXApi = new OrderCancelPXApi(this, simpleOnNextListenerCancleOrderPX);
            orderCancelPXApi.setCache(false);
            orderCancelPXApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(orderCancelPXApi);

        }

    }

    private void againBuyResq(Context context, String orderId) {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> map = new HashMap<>();
            if (TextUtils.isEmpty(orderId)) {
                ToastTools.showToast(context, "没有订单ID");
                return;
            }
            map.put("orderId", orderId);
            map.put("token", getSharedPreferencesUtil().getLogintoken());


            final BuyAgainApi buyAgainApi = new BuyAgainApi(this, simpleOnNextListenerBuyAgain);
            buyAgainApi.setCache(false);
            buyAgainApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(buyAgainApi);

        }
    }

    private void toPayPX(int orderType, String orderSn) {

        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> paramsBody = new HashMap<>();
            if (TextUtils.isEmpty(orderSn)) {
                ToastTools.showToast(context, "没有获取到订单编号");
                return;
            }
            this.orderSn = orderSn;
            this.orderType = orderType;
//            paramsBody.put("orderId", orderId+"");
            paramsBody.put("token", getSharedPreferencesUtil().getLogintoken());

            //获取支付方式
            final ToPayPXApi toPayPXApi = new ToPayPXApi(this, simpleOnNextListenerPayWayPX);
            toPayPXApi.setCache(false);
            toPayPXApi.setMap(paramsBody);
            HttpManager.getInstance().doHttpDeal(toPayPXApi);


        }
    }

    private void toPay(int orderType, int orderId) {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> paramsBody = new HashMap<>();
            if (orderId == -1) {
                ToastTools.showToast(context, "没有获取到支付ID");
                return;
            }
            this.orderId = orderId;
            this.orderType = orderType;
            paramsBody.put("orderId", orderId + "");
            paramsBody.put("token", getSharedPreferencesUtil().getLogintoken());

            //获取支付方式
            final ToPayApi toPayApi = new ToPayApi(this, simpleOnNextListenerPayWay);
            toPayApi.setCache(false);
            toPayApi.setMap(paramsBody);
            HttpManager.getInstance().doHttpDeal(toPayApi);


        }
    }

    private void addCar(String skuStr, String orderType) {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> map = new HashMap<>();
            map.put("skuStr", skuStr);
            map.put("orderType", orderType);
//            是否再次购买（0/1）
            map.put("buyAgain", "1");
            map.put("token", getSharedPreferencesUtil().getLogintoken());
            map.put("deviceId", DeviceUtils.getIMEString(context));

            final AddCarApi addCarApi = new AddCarApi(this, simpleOnNextListenerAddCar);
            addCarApi.setCache(false);
            addCarApi.setMap(map);
            HttpManager.getInstance().doHttpDeal(addCarApi);
        }
    }

    private void selectPay(PayWayBean data) {


        View inflate = LayoutInflater.from(context).inflate(R.layout.select_pay_way_layout, null);
        RelativeLayout rl_close = (RelativeLayout) inflate.findViewById(R.id.rl_close);
//        final ImageView chat_btn = (ImageView) inflate.findViewById(R.id.chat_btn);
//        final ImageView ali_btn = (ImageView) inflate.findViewById(R.id.ali_btn);
//        final ImageView zhuanzhang_btn = (ImageView) inflate.findViewById(R.id.zhuanzhang_btn);
//        final ImageView yue_btn = (ImageView) inflate.findViewById(R.id.yue_btn);
//        final ImageView shop_pay_btn = (ImageView) inflate.findViewById(R.id.shop_pay_btn);
        RecyclerView recy_list = inflate.findViewById(R.id.recy_list);
        final ImageView iv_agree = (ImageView) inflate.findViewById(R.id.iv_agree);
        final TextView tv_submit_order = (TextView) inflate.findViewById(R.id.tv_submit_order);
        final TextView tv_pay_agreen = (TextView) inflate.findViewById(R.id.tv_pay_agreen);
//        final TextView tv_order_price = (TextView) inflate.findViewById(R.id.tv_order_price);
        final EditText et_use_yue = (EditText) inflate.findViewById(R.id.et_use_yue);
        final LinearLayout ll_use_yue = (LinearLayout) inflate.findViewById(R.id.ll_use_yue);

        if (order != null) {
            tv_submit_order.setText("确认付款 ¥" + MoneyShowUtils.dealNumber(order.getOrderAmount() + ""));
        }

        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(context);
        recy_list.setLayoutManager(linearLayoutManager);
        payWayAdapter = new PayWayAdapter(context, paymentList);
        recy_list.setAdapter(payWayAdapter);
        payWayAdapter.setOrderType(orderType);

        //只有ordertype==4才有余额支付
        if (orderType != 5) {
            if (orderType == 4) {
                ll_use_yue.setVisibility(View.VISIBLE);
            } else {
                ll_use_yue.setVisibility(View.GONE);
            }
        } else {
            ll_use_yue.setVisibility(View.GONE);
        }


        payWayAdapter.setYueMoney(data.getUserMoney());
        payWayAdapter.setOrderPrice(order.getOrderAmount() + "");
        payWayAdapter.notifyDataSetChanged();


        iv_agree.setSelected(isAgreement);
//        chat_btn.setRJCPSelected(true);
        commonPop(inflate);
        //关闭按钮
        rl_close.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogCustom.showDoubleDialog(context, "", "确认放弃付款？", "确认离开", "继续支付", new DialogCustom.CustomDialogDouble() {
                    @Override
                    public void rightButtonClicked() {

                    }

                    @Override
                    public void leftButtonClicked() {
                       /* if (orderType!=5){
                            Intent intent = new Intent(context, OrderDetailsActivity.class);
                            intent.putExtra(ORDER_ID, orderId + "");

                            ((Activity) context).startActivityForResult(intent, COMMENT_FORCODE);
                        }else {
                            Intent intent = new Intent(context, OrderDetailsPXActivity.class);
                            intent.putExtra(ORDER_SN, orderSn + "");

                            ((Activity) context).startActivityForResult(intent, COMMENT_FORCODE);
                        }*/
                        popupWindow.dismiss();
                    }
                });
            }
        });
        et_use_yue.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

                if (TextUtils.isEmpty(s.toString())) {
                    tv_submit_order.setText("确认付款 ¥" + MoneyShowUtils.dealNumber(order.getOrderAmount() + ""));
                    return;
                }
                if ((Double.parseDouble(order.getOrderAmount() + "") - Double.parseDouble(s.toString())) < 0) {
                    ToastTools.showToast(context, "使用余额的金额应不能大于付款金额");
                    et_use_yue.setText(order.getOrderAmount() + "");
                } else if ((data.getUserMoney() - Double.parseDouble(s.toString())) < 0) {
                    ToastTools.showToast(context, "使用余额的金额应不能大于所剩余额");
                    et_use_yue.setText(data.getUserMoney() + "");
                } else {
                    if (payId != -1) {
                        tv_submit_order.setText("确认付款 ¥" + MoneyShowUtils.dealNumber((Double.parseDouble(order.getOrderAmount() + "") - Double.parseDouble(s.toString())) + ""));
                    }
                }

            }

            @Override
            public void afterTextChanged(Editable s) {

            }
        });
        //列表点击事件
        payWayAdapter.setOnClickItem(new PayWayAdapter.OnClickItem() {
            @Override
            public void OnClickListion(View view, int postion) {
                if (paymentList != null && paymentList.size() > 0) {
                    payId = paymentList.get(postion).getPayId();
                }
                payWayAdapter.setmSelectedPos(postion);
                if (payId == 5) {

                    et_use_yue.setText(MoneyShowUtils.dealNumber(order.getOrderAmount() + ""));

                } else {
                    et_use_yue.setText("");
                }
                payWayAdapter.notifyDataSetChanged();
            }
        });
        //支付协议
        tv_pay_agreen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(context, PayAgreenActivity.class);
                context.startActivity(intent);
            }
        });
//        chat_btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                chat_btn.setRJCPSelected(true);
//                ali_btn.setRJCPSelected(false);
//                zhuanzhang_btn.setRJCPSelected(false);
//                yue_btn.setRJCPSelected(false);
//                shop_pay_btn.setRJCPSelected(false);
//                Toast.makeText(OrderConfirmActivity.this, "点击了", Toast.LENGTH_SHORT).show();
//            }
//        });
//        ali_btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                chat_btn.setRJCPSelected(false);
//                ali_btn.setRJCPSelected(true);
//                zhuanzhang_btn.setRJCPSelected(false);
//                yue_btn.setRJCPSelected(false);
//                shop_pay_btn.setRJCPSelected(false);
//            }
//        });
//        zhuanzhang_btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                chat_btn.setRJCPSelected(false);
//                ali_btn.setRJCPSelected(false);
//                zhuanzhang_btn.setRJCPSelected(true);
//                yue_btn.setRJCPSelected(false);
//                shop_pay_btn.setRJCPSelected(false);
//            }
//        });
//        yue_btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                chat_btn.setRJCPSelected(false);
//                ali_btn.setRJCPSelected(false);
//                zhuanzhang_btn.setRJCPSelected(false);
//                yue_btn.setRJCPSelected(true);
//                shop_pay_btn.setRJCPSelected(false);
//            }
//        });
//        shop_pay_btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                chat_btn.setRJCPSelected(false);
//                ali_btn.setRJCPSelected(false);
//                zhuanzhang_btn.setRJCPSelected(false);
//                yue_btn.setRJCPSelected(false);
//                shop_pay_btn.setRJCPSelected(true);
//            }
//        });
        //同意条款
        iv_agree.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isAgreement = !isAgreement;
                iv_agree.setSelected(isAgreement);
            }
        });
        //付款提交
        tv_submit_order.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String useYue = et_use_yue.getText().toString().trim();
                String submitMoney = tv_submit_order.getText().toString().trim();
                submitMoney = submitMoney.replace("确认付款 ¥", "");
              /*  if (Double.parseDouble(submitMoney) <= 0) {
                    if (payId == 2 || payId == 3 || payId == 4 || payId == 6) {
                        ToastTools.showLongToast(OrderDetailsActivity.this, "支付金额为0，请选择余额支付");
                        return;
                    }

                }*/
                if (!iv_agree.isSelected()) {
                    ToastTools.showLongToast(context, "同意条款才能进行支付");
                    return;
                } else if (payId != -1 && payId == 5) {
                  /*  if (!TextUtils.isEmpty(useYue)){
                        ToastTools.showLongToast(context,"选择余额支付后无需填写余额");
                        return;
                    }else*/
                    if (Double.parseDouble(submitMoney) > data.getUserMoney()) {
                        ToastTools.showLongToast(context, "余额不足请充值或选择其他支付方式！");
                        return;
                    }
                } else if (payId != -1 && payId != 5) {
                    if (!TextUtils.isEmpty(useYue) && !TextUtils.isEmpty(order.getOrderAmount() + "")) {
                        if (Double.parseDouble(useYue) > Double.parseDouble(order.getOrderAmount() + "")) {
                            ToastTools.showLongToast(context, "您选择了混合的支付方式，请填写正确的金额");
                            return;
                        }
                    }

                }
                if (orderType != 5) {
                    if (payWayAdapter.getBalancePayId() == 5 || payId == 5) {
                        paySubmit(useYue);
                    } else {
                        paySubmit(useYue);
                    }

                } else {
                    if (payWayAdapter.getBalancePayId() == 5 || payId == 5) {
                        paySubmitPX(useYue);
                    } else {
                        paySubmitPX(useYue);

                    }
                }

            }
        });


    }

    private void paySubmitPX(String useYue) {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> paramsBody = new HashMap<>();
            if (TextUtils.isEmpty(orderSn)) {
                ToastTools.showToast(context, "没有获取到支付ID");
                return;
            }
            paramsBody.put("orderNumber", orderSn);
            paramsBody.put("token", getSharedPreferencesUtil().getLogintoken());

            if (payWayAdapter.getBalancePayId() == -1 && payId == -1) {
                return;
            }
            paramsBody.put("payId", payId + "");

            //支付提交
            final PaySubmitPXApi paySubmitPXApi = new PaySubmitPXApi(this, simpleOnNextListenerPaySubmitPX);
            paySubmitPXApi.setCache(false);
            paySubmitPXApi.setMap(paramsBody);
            HttpManager.getInstance().doHttpDeal(paySubmitPXApi);


        }

    }

    private void paySubmit(String use_yue) {
        if (!getSharedPreferencesUtil().getLogintoken().isEmpty()) {
            Map<String, String> paramsBody = new HashMap<>();
            if (orderId == -1) {
                ToastTools.showToast(context, "没有获取到支付ID");
                return;
            }
            paramsBody.put("orderId", orderId + "");
            paramsBody.put("token", getSharedPreferencesUtil().getLogintoken());

            if (payWayAdapter.getBalancePayId() == -1 && payId == -1) {
                return;
            }
            paramsBody.put("payId", payId + "");
            if (!TextUtils.isEmpty(use_yue)) {
                paramsBody.put("balance", use_yue);
            } else {
                paramsBody.put("balance", 0 + "");
            }

            //支付提交
            final PaySubmitApi paySubmitApi = new PaySubmitApi(this, simpleOnNextListenerPaySubmit);
            paySubmitApi.setCache(false);
            paySubmitApi.setMap(paramsBody);
            HttpManager.getInstance().doHttpDeal(paySubmitApi);


        }
    }

    //查看物流
    HttpOnNextListener simpleOnNextListenerLookWuliu = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }
        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };
    //培训取消订单
    HttpOnNextListener simpleOnNextListenerCancleOrderPX = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }
            ToastTools.showToast(context, "取消订单成功");
            InformUpdate informUpdate = new InformUpdate();
            informUpdate.setEventType(informUpdate.CANCEL_ORDER_INFORM);
            EventBus.getDefault().post(informUpdate);
            popupWindow.dismiss();
        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };

    //再次购买
    HttpOnNextListener simpleOnNextListenerBuyAgain = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }
            final BuyAgainBean data = (BuyAgainBean) subjects.getData();
            if (subjects.getCode().equals("0000")) {
                if (data.getOrderType() == 4) {

                    boolean isSkuStr = data.isIsSkuStr();
                    if (subjects.getMsg().length() > 0) {
                        if (isSkuStr) {
                            DialogCustom.showDoubleDialog(context, "提示", subjects.getMsg() + "是否继续再次购买?", "取消", "确定", new DialogCustom.CustomDialogDouble() {
                                @Override
                                public void rightButtonClicked() {
                                    //添加购物车
                                    addCar(data.getSkuStr(), data.getOrderType() + "");

                                }

                                @Override
                                public void leftButtonClicked() {

                                }
                            });
                        } else {
                            ToastTools.showToast(context, subjects.getMsg());
                        }
                    } else {
                        //添加购物车
                        addCar(data.getSkuStr(), data.getOrderType() + "");
                    }
                } else {
                    if (subjects.getMsg().length() > 0) {
                        ToastTools.showToast(context, subjects.getMsg());
                    } else {
                        //跳转确认订单页
                        Intent intent = new Intent(context, OrderConfirmActivity.class);
                        intent.putExtra("orderType", data.getOrderType() + "");
                        intent.putExtra("skuStr", data.getSkuStr());
                        intent.putExtra("againBuy", AGAINBUY);
                        context.startActivity(intent);
                    }
                }
            } else {
                ToastTools.showToast(context, subjects.getMsg());
            }
        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };

    //培训获取支付方式
    HttpOnNextListener simpleOnNextListenerPayWayPX = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            paymentList.clear();
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }

            PayWayBean data = (PayWayBean) subjects.getData();
            paymentList.addAll(data.getPaymentList());
            //选择支付
            selectPay(data);


        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };

    //获取支付方式
    HttpOnNextListener simpleOnNextListenerPayWay = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            paymentList.clear();
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }

            PayWayBean data = (PayWayBean) subjects.getData();
            paymentList.addAll(data.getPaymentList());
            //选择支付
            selectPay(data);


        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };

    //添加购物车
    HttpOnNextListener simpleOnNextListenerAddCar = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {

            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }

            //跳转购物车
            Intent intent = new Intent(context, ShoppingCarActivity.class);
            context.startActivity(intent);
        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };

    //培训支付提交
    HttpOnNextListener simpleOnNextListenerPaySubmitPX = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            paymentList.clear();
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }
            popupWindow.dismiss();
            if ((PayVo) subjects.getData() != null) {
                final PayVo payVo = (PayVo) subjects.getData();
                if (javaPayUtil == null) {
                    javaPayUtil = new JavaPayUtil(context, new JavaPayUtil.PaySuccessCallBack() {
                        @Override
                        public void paySuccess() {
//                            Intent intent = new Intent();
//                            setResult(MEMBER_REFRESH, intent);
//                            finish();
//                            ToastTools.showToast(OrderConfirmActivity.this,"支付成功");
//                            new Intent(OrderConfirmActivity.this,)
                            if (orderId != -1) {
                                ToastTools.showToast(context, "没有获取到支付ID");
                                return;
                            }

                            Intent intent = new Intent(context, PaySucceedActivity.class);
                            intent.putExtra("order_id", orderId + "");
                            intent.putExtra("order_type", payVo.getOrderType());
                            context.startActivity(intent);

                        }

                        @Override
                        public void expertPaySuccess(String consultType) {

                        }

                        @Override
                        public void payCancel() {
                            if (orderId != -1) {
                                ToastTools.showToast(context, "没有获取到支付ID");
                                return;
                            }

                            Intent intent = new Intent(context, PaySucceedActivity.class);
                            intent.putExtra("order_id", orderId + "");
                            intent.putExtra("order_type", payVo.getOrderType());
                            context.startActivity(intent);

                        }
                    });
                }

                //orderType用来区分是否有余额支付
                if (orderType != -1) {
                    payVo.setOrderType(orderType);
                }
                String payId = payVo.getPayId();
                int payID = Integer.parseInt(payId);
                //payId  2  微信支付   3     支付宝     4    银行汇款/转账     6   到店支付     5   余额支付
                if (payID == 2) {
                    javaPayUtil.payByWay(payVo, "WeChat");
                } else if (payID == 3) {
                    javaPayUtil.payByWay(payVo, "Alipay");
                } else if (payID == 4) {
                    Intent intent = new Intent(context, BankPayActivity.class);
                    intent.putExtra("order_id", orderId + "");
                    intent.putExtra("order_sn", orderSn + "");
                    intent.putExtra("orderType", orderType + "");
                    context.startActivity(intent);

                } else if (payWayAdapter.getBalancePayId() == 5 || payID == 5) {
                    if (orderId == -1) {
                        ToastTools.showToast(context, "没有获取到订单ID");
                        return;
                    }
                    Intent intent = new Intent(context, PaySucceedActivity.class);
                    intent.putExtra("order_id", orderId + "");
                    intent.putExtra("order_type", orderType);
                    context.startActivity(intent);
                } else if (payID == 6) {
                    Intent intent = new Intent(context, ShopPayActivity.class);
                    context.startActivity(intent);
                }

            }
        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };

    //支付提交
    HttpOnNextListener simpleOnNextListenerPaySubmit = new HttpOnNextListener<BaseResultEntity>() {
        @Override
        public void onNext(BaseResultEntity subjects) {
            paymentList.clear();
            if (!subjects.getCode().equals(ConstantsUtils.STATUS_SUCCESS_0000)) {
                ToastTools.showToast(context, subjects.getMsg());
                return;
            }
            popupWindow.dismiss();
            if ((PayVo) subjects.getData() != null) {
                final PayVo payVo = (PayVo) subjects.getData();
                if (javaPayUtil == null) {
                    javaPayUtil = new JavaPayUtil(context, new JavaPayUtil.PaySuccessCallBack() {
                        @Override
                        public void paySuccess() {
//                            Intent intent = new Intent();
//                            setResult(MEMBER_REFRESH, intent);
//                            finish();
//                            ToastTools.showToast(OrderConfirmActivity.this,"支付成功");
//                            new Intent(OrderConfirmActivity.this,)
                            if (orderId == -1) {
                                ToastTools.showToast(context, "没有获取到支付ID");
                                return;
                            }
                            Intent intent = new Intent(context, PaySucceedActivity.class);
                            intent.putExtra("order_id", orderId + "");
                            intent.putExtra("order_type", payVo.getOrderType());
                            context.startActivity(intent);
                        }

                        @Override
                        public void expertPaySuccess(String consultType) {

                        }

                        @Override
                        public void payCancel() {
                            if (orderId == -1) {
                                ToastTools.showToast(context, "没有获取到支付ID");
                                return;
                            }
                            Intent intent = new Intent(context, PaySucceedActivity.class);
                            intent.putExtra("order_id", orderId + "");
                            intent.putExtra("order_type", payVo.getOrderType());
                            context.startActivity(intent);
                        }
                    });
                }

                //orderType用来区分是否有余额支付
                if (orderType != -1) {
                    payVo.setOrderType(orderType);
                }
                String payId = payVo.getPayId();
                int payID = Integer.parseInt(payId);
                //payId  2  微信支付   3     支付宝     4    银行汇款/转账     6   到店支付     5   余额支付
                if (payID == 2) {
                    javaPayUtil.payByWay(payVo, "WeChat");
                } else if (payID == 3) {
                    javaPayUtil.payByWay(payVo, "Alipay");
                } else if (payID == 4) {
                    Intent intent = new Intent(context, BankPayActivity.class);
                    intent.putExtra("order_id", orderId + "");
                    intent.putExtra("orderType", orderType + "");
                    context.startActivity(intent);

                } else if (payWayAdapter.getBalancePayId() == 5 || payID == 5) {
                    if (orderId == -1) {
                        ToastTools.showToast(context, "没有获取到订单ID");
                        return;
                    }
                    Intent intent = new Intent(context, PaySucceedActivity.class);
                    intent.putExtra("order_id", orderId + "");
                    intent.putExtra("order_type", orderType);
                    context.startActivity(intent);
                } else if (payID == 6) {
                    Intent intent = new Intent(context, ShopPayActivity.class);
                    intent.putExtra("order_id", orderId + "");
                    intent.putExtra("orderType", orderType + "");
                    context.startActivity(intent);
                }

            }
        }


        @Override
        public void onCacheNext(String cache) {


        }


        @Override
        public void onError(final Throwable e) {
            Log.e("cjx", e.getMessage());
        }
    };

    /**
     * 拨打电话（跳转到拨号界面，用户手动点击拨打）
     *
     * @param phoneNum 电话号码
     */
    public void callPhone(String phoneNum) {
        Intent intent = new Intent(Intent.ACTION_DIAL);
        Uri data = Uri.parse("tel:" + phoneNum);
        intent.setData(data);
        context.startActivity(intent);
    }
    public String dealString(String value){
        if (TextUtils.isEmpty(value)){
            return "";
        }else if (value.equals("null")){
            return "";
        }else if (value.equals("(null)")){
            return "";
        }else if (value.equals("<null>")){
            return "";
        }else {
            return value;
        }

    }
}

